package com.lingjtx.common.thread.pooling;

import com.lingjtx.common.thread.core.PoolNameConst;
import com.lingjtx.common.thread.core.ThreadPoolManager;

import java.net.http.HttpClient;
import java.time.Duration;

/**
 * http连接池
 */
public class HttpClientFactory implements ObjectFactory<HttpClient> {

    private final ThreadPoolManager threadPoolManager;

    public HttpClientFactory(ThreadPoolManager threadPoolManager) {
        this.threadPoolManager = threadPoolManager;
    }

    @Override
    public HttpClient create() {
        return HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
                .connectTimeout(Duration.ofSeconds(15))     // 连接超时
                .executor(threadPoolManager.getOrCreate(PoolNameConst.POOLING_HTTP)) // 自定义线程池
                .followRedirects(HttpClient.Redirect.NORMAL)
                .build();
    }

    @Override
    public boolean validate(HttpClient client) {
        // HttpClient 是线程安全的，一般无需校验
        return client != null;
    }

    @Override
    public void destroy(HttpClient client) {
        client.shutdown();
        // 若引用线程池，可根据情况释放线程池
        shutdown();
    }

    @Override
    public void shutdown() {
        try {
            threadPoolManager.shutdown(PoolNameConst.POOLING_HTTP); // 优雅关闭线程池
        } catch (Exception ignored) {
        }
    }
}
